The delete
operator can be used to remove a property from any object. Arrays are objects, so the delete
operator can be
used on them too.
When you delete an element from an array using the delete
keyword, it will remove the value but still leave behind an empty slot at
that index. Therefore, a hole will be created in the array because the indexes won’t be shifted to reflect the deletion. This means that the array
will still have that index, but the value will be undefined
.
Arrays that have gaps or missing indexes between elements are known as sparse arrays.
let myArray = ['a', 'b', 'c', 'd'];
delete myArray[2]; // Noncompliant: myArray => ['a', 'b', undefined, 'd']
console.log(myArray[2]); // expected value was 'd' but output is undefined
The proper method for removing an element from an array should be one of the following:
-
Array.prototype.splice()
- removes element(s) from an array at certain indexe(s)
-
Array.prototype.pop()
- removes the last element from an array
-
Array.prototype.shift()
- removes the first element from an array
Note that these methods mutate arrays in-place. Alternatively, you could create new arrays using copying methods and exclude the element you want
to remove.
let myArray = ['a', 'b', 'c', 'd'];
// removes 1 element from index 2
removed = myArray.splice(2, 1); // myArray => ['a', 'b', 'd']
console.log(myArray[2]); // outputs 'd'